/**
 * Application launcher.
 */

/* 播放事件 */
var playDcm;
function play(dcmApp){
	if(!$("#play").is(":checked")){
		palyState = false;
		clearInterval(playDcm);
		$(".canvasLayer").remove();
		return;
	}
	var num = Number($("#sliceRange").val());
	var manNum = Number($("#sliceRange").attr("max"));
	$(".layerContainer").append("<div class='canvasLayer'></div>")
	playDcm = setInterval(function(){
		num++;
		if(num > manNum){
			num = 0;
		}
		$("#sliceRange").val(num);
		var pos = dcmApp.getViewController().getCurrentPosition();
		pos.k = num;
		dcmApp.getViewController().setCurrentPosition(pos);
		borderRange("#dwv_"+num);
		$("#rangeVal").html((num+1)+"/"+(manNum+1))
	},1000);
}

/* 导航 切换图片 */
function dcmNav(){
	var app = [];
	$(".nav").find("li").remove();
	$("input[name*='dcmUrl_']").each(function(i){
		$(".nav").append("<li id='dwv_" + i + "'><div class='layerContainer'><canvas class='imageLayer'></canvas></div></li>");
    	var apps = $(this).val();
    	if(apps){
	    	apps = apps.split(",")[0].split(",");
	    }else{
	    	return false;
	    }
    	app["dcmUrl"+i] = new dwv.App();
    	app["dcmUrl"+i].loadURLs(apps);
    	app["dcmUrl"+i].init({"containerDivId": "dwv_"+i});
    	var size = dwv.gui.getWindowSize();
    	$("#dwv_"+i).find(".layerContainer").height(size.height);
	});
	$(".nav").find("li").eq(0).addClass("fontBorder");
	/*for(var i in dcmUrl){
    	$(".nav").append("<li id='dwv_" + i + "'><div class='layerContainer'><canvas class='imageLayer'></canvas></div></li>");
    	var apps = dcmUrl[i].split(",");
    	app["dcmUrl"+i] = new dwv.App();
    	app["dcmUrl"+i].loadURLs(apps);
    	app["dcmUrl"+i].init({"containerDivId": "dwv_"+i});
    	var size = dwv.gui.getWindowSize();
    	$("#dwv_"+i).find(".layerContainer").height(size.height);
    }*/  
}

/* 导航 切换图片 的边框变化 */
function borderRange(thiss){
	/*$("li[id*='dwv_']").removeClass("fontBorder");
	$(thiss).addClass("fontBorder")*/
}

// start app function
function startApp() {
    // translate page
    dwv.i18nPage();
    // main application
    var myapp = new dwv.App();
    var dcmUrl = $("input[name*='dcmUrl_']").eq(0).val();
    if(dcmUrl){
    	dcmUrl = dcmUrl.split(",")
    }else{
    	return false;
    }

	myapp.loadURLs(dcmUrl);
	
    // display loading time
    var listener = function (event) {
    	$("#htmlBg").remove();
    	var htmlBg = "<div id='htmlBg' style='position:fixed;left:0;top:0;width: 100%;height:"+ $(window).height() +"px;background:#252525;z-index:9999999;display:flex;align-items:center;justify-content:center;'><p>文件加载中···</p></div>";
    	$("body").append(htmlBg);
        if (event.type === "load-progress") {
            
        }
        else if(event.type === "draw-move"){
        	console.log("buzhidao")
        }
        else if(event.type === "load-end"){
        	console.log($("#htmlBg").length)
        	$("#htmlBg").remove();
        	var ranges = document.getElementById("sliceRange");
			ranges.min = 0;
			ranges.oninput = function () {
			    var pos = myapp.getViewController().getCurrentPosition();
				pos.k = ranges.value;
				myapp.getViewController().setCurrentPosition(pos);
				borderRange("#dwv_"+pos.k);
				var rangeMax = Number(ranges.max)+1;
	        	var rangeVal = Number(ranges.value)+1;
	        	$("#rangeVal").html(rangeVal+"/"+rangeMax);
	        	if(playDcm){
					clearInterval(playDcm);
				}
				$("#play").prop("checked",false);
				$(".canvasLayer").remove();
			}
			
			
        	ranges.max = myapp.getImage().getGeometry().getSize().getNumberOfSlices() - 1;
        	var pos2 = myapp.getViewController().getCurrentPosition();
			pos2.k = 0;
			myapp.getViewController().setCurrentPosition(pos2);
        	ranges.value = 0;
        	if(ranges.max == 0){
        		$("#play").attr("disabled","disabled");
        		$("#rangeVal").html("");
        	}else{
        		$("#play").removeAttr("disabled");
        		var rangeMax = Number(ranges.max)+1;
        		var rangeVal = Number(ranges.value)+1;
        		$("#rangeVal").html(rangeVal+"/"+rangeMax);
        	}
        	$(".refresh").remove();
        	$(".wenhao").remove();
        	$(".toolbar").append("<a class='refresh ui-btn ui-btn-inline ui-btn-icon-notext ui-mini'><div></div></a><a class='wenhao ui-btn ui-btn-inline ui-btn-icon-notext ui-mini'><div></div></a>");
        	$("select.presetSelect option[value*='Default']").each(function(){
        		if($(this).val() != "Default0"){
        			$(this).remove();
        		}
        	});
        	
        	$(".layerContainer").css("max-height",($("body").height()-190)+"px");
        }
        else if(event.type === "slice-change"){
        	ranges.value = myapp.getViewController().getCurrentPosition().k;
        	borderRange("#dwv_"+ranges.value);
        	var rangeMax = Number(ranges.max)+1;
	        var rangeVal = Number(ranges.value)+1;
	        $("#rangeVal").html(rangeVal+"/"+rangeMax);
	        if(playDcm){
				clearInterval(playDcm);
			}
			$("#play").prop("checked",false);
			$(".canvasLayer").remove();
        }
        else {
        	console.log(myapp+":1")
            console.timeEnd("load-data");
        }
    };
	/* 导航 切换图片 点击事件 */
	$(".nav").on("click","li[id*='dwv_']",function(){
		if(playDcm){
			clearInterval(playDcm);
		}
		$("#play").prop("checked",false);
		$(".canvasLayer").remove();
		var index = $("li[id*='dwv_']").index(this)
		var dcmUrls = $("input[name*='dcmUrl_']").eq(index).val().split(",");
		$(".nav li").removeClass("fontBorder");
		$(".nav li").eq(index).addClass("fontBorder");
		myapp.loadURLs(dcmUrls);
	})
			
	/* 播放按钮点击事件 */
	$("#play").click(function(){
		play(myapp);
	})
	
	/* 刷新页面 */
	$("body").on("click",".refresh",function(){
		if(playDcm){
			clearInterval(playDcm);
		}
		$("#play").prop("checked",false);
		$(".canvasLayer").remove();
		var liIndex = $("li[id*=dwv_]").index($(".fontBorder"));
		var refreshDcmUrl = $("input[name*='dcmUrl_']").eq(liIndex).val();
		if(refreshDcmUrl != ""){
			refreshDcmUrl = refreshDcmUrl.split(",");
			myapp.loadURLs(refreshDcmUrl);
		}
	});
	
	/* 触发select事件关闭播放 */
	$("body").on("change","select",function(){
		if(playDcm){
			clearInterval(playDcm);
		}
		$("#play").prop("checked",false);
		$(".canvasLayer").remove();
	})
	/* 触发a事件关闭播放 */
	$("body").on("click","a",function(){
		if(playDcm){
			clearInterval(playDcm);
		}
		$("#play").prop("checked",false);
		$(".canvasLayer").remove();
	});
	
	$(".imageLayer").click(function(){
		if(playDcm){
			clearInterval(playDcm);
		}
		$("#play").prop("checked",false);
		$(".canvasLayer").remove();
	});
	
    // before myapp.init since it does the url load
    myapp.addEventListener("load-start", listener);
    myapp.addEventListener("load-end", listener);

    // also available:
    //myapp.addEventListener("load-progress", listener);
    //myapp.addEventListener("draw-create", listener);
    //myapp.addEventListener("draw-move", listener);
    //myapp.addEventListener("draw-change", listener);
    //myapp.addEventListener("draw-delete", listener);
    //myapp.addEventListener("wl-width-change", listener);
    //myapp.addEventListener("wl-center-change", listener);
    //myapp.addEventListener("colour-change", listener);
    //myapp.addEventListener("position-change", listener);
    //myapp.addEventListener("slice-change", listener);
    //myapp.addEventListener("frame-change", listener);
    //myapp.addEventListener("zoom-change", listener);
    //myapp.addEventListener("offset-change", listener);
    //myapp.addEventListener("filter-run", listener);
    //myapp.addEventListener("filter-undo", listener);

    // initialise the application
    var options = {
        "containerDivId": "dwv",
        "fitToWindow": true,
        "gui": ["tool", "load", "help", "undo", "version", "tags", "drawList"],
        "loaders": ["File", "Url", "GoogleDrive", "Dropbox"],
        "tools": [ "WindowLevel", "ZoomAndPan", "Draw"],
        "filters": ["Threshold", "Sharpen", "Sobel"],
        "shapes": ["Ruler", "Protractor", "Rectangle", "Ellipse", "FreeHand"],
        "isMobile": true
        //"defaultCharacterSet": "chinese"
    };
    if ( dwv.browser.hasInputDirectory() ) {
        options.loaders.splice(1, 0, "Folder");
    }
    myapp.init(options);

	
    
    
}

// Image decoders (for web workers)
dwv.image.decoderScripts = {
    "jpeg2000": "../../decoders/pdfjs/decode-jpeg2000.js",
    "jpeg-lossless": "../../decoders/rii-mango/decode-jpegloss.js",
    "jpeg-baseline": "../../decoders/pdfjs/decode-jpegbaseline.js"
};

// status flags
var domContentLoaded = false;
var i18nInitialised = false;
// launch when both DOM and i18n are ready
function launchApp() {
    if ( domContentLoaded && i18nInitialised ) {
        startApp();
    }
}
// i18n ready?
dwv.i18nOnInitialised( function () {
    // call next once the overlays are loaded
    var onLoaded = function (data) {
        dwv.gui.info.overlayMaps = data;
        i18nInitialised = true;
        launchApp();
    };
    // load overlay map info
    $.getJSON( dwv.i18nGetLocalePath("overlays.json"), onLoaded )
    .fail( function () {
        console.log("Using fallback overlays.");
        $.getJSON( dwv.i18nGetFallbackLocalePath("overlays.json"), onLoaded );
    });
});

// check browser support
dwv.browser.check();
// initialise i18n
dwv.i18nInitialise();

// DOM ready?
$(document).ready( function() {
	$("#htmlBg").remove();
    var htmlBg = "<div id='htmlBg' style='position:fixed;left:0;top:0;width: 100%;height:"+ $(window).height() +"px;background:#252525;z-index:9999999;display:flex;align-items:center;justify-content:center;'><p>文件加载中···</p></div>";
    $("body").append(htmlBg);
    domContentLoaded = true;
    launchApp();
    dcmNav();
});
